package top.go2do.auth.business.captcha.service;

import cn.hutool.captcha.CaptchaUtil;
import cn.hutool.captcha.LineCaptcha;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import top.go2do.auth.business.captcha.module.CaptchaResult;
import top.go2do.auth.configProperties.AuthModuleConfig;
import top.go2do.common.utils.MySecureRandomStringUtils;

import java.util.concurrent.TimeUnit;

import static top.go2do.common.redis.RedisKey.getCaptchaIdKey;

/**
 * @Description
 * @Author xingyj
 * @CreateTime 2025/4/1 12:45
 */
@Slf4j
@Service
public class CaptchaServiceImpl implements CaptchaService{
    @Autowired
    private RedisTemplate redisTemplate;

    @Autowired
    private AuthModuleConfig authConfig;

    @Override
    public String generateAndSaveCaptcha(Long userId) {
        LineCaptcha lineCaptcha = CaptchaUtil.createLineCaptcha(authConfig.getCaptchaWidth(),
                authConfig.getCaptchaHeight(), authConfig.getCaptchaCodeCount(), authConfig.getCaptchaLineCount());
        String imgBase64 = lineCaptcha.getImageBase64Data();
        String code = lineCaptcha.getCode();
//        setCaptchaCode(userId, code);
        return imgBase64;
    }

    @Override
    public String getCaptchaCode(Long userId) {
        Object result = redisTemplate.opsForValue().get(getCaptchaIdKey(userId));
        return result == null ? "" : String.valueOf(result);
    }

    @Override
    public CaptchaResult generateAndSaveCaptcha() {
        LineCaptcha lineCaptcha = CaptchaUtil.createLineCaptcha(authConfig.getCaptchaWidth(),
                authConfig.getCaptchaHeight(), authConfig.getCaptchaCodeCount(), authConfig.getCaptchaLineCount());
        String imgBase64 = lineCaptcha.getImageBase64Data();
        String captchaId = MySecureRandomStringUtils.generate(8);
        String code = lineCaptcha.getCode();
        setCaptchaCode(captchaId, code);
        CaptchaResult result = new CaptchaResult();
        result.setCaptchaId(captchaId);
        result.setCaptchaImage(imgBase64);
        return result;
    }

    private void setCaptchaCode(String captchaId, String code) {
        redisTemplate.opsForValue().set(getCaptchaIdKey(captchaId), code, authConfig.getCaptchaTimeoutSecond(), TimeUnit.SECONDS);
    }

}
